package com.ocean.previewElement.service.impl;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ocean.common.utils.DictUtils;
import com.ocean.common.utils.file.WordGenerator;
import com.ocean.common.utils.uuid.IdUtils;
import com.ocean.nc.domain.ONcFile;
import com.ocean.nc.mapper.ONcFileMapper;
import com.ocean.previewElement.domain.CreateWorkItemDto;
import com.ocean.previewElement.domain.PreviewData;
import com.ocean.product.domain.OProduct;
import com.ocean.product.mapper.OProductMapper;
import com.ocean.workOrder.domain.OWorkOrderItem;
import org.apache.commons.io.IOUtils;
import org.apache.tools.ant.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ocean.previewElement.mapper.OPreviewElementMapper;
import com.ocean.previewElement.domain.OPreviewElement;
import com.ocean.previewElement.service.IOPreviewElementService;
import com.ocean.common.core.text.Convert;

import static cn.hutool.core.io.FileTypeUtil.getType;

/**
 * 预览要素Service业务层处理
 *
 * @author ocean
 * @date 2023-02-16
 */
@Service
public class OPreviewElementServiceImpl implements IOPreviewElementService
{
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private OPreviewElementMapper oPreviewElementMapper;
    @Autowired
    private OProductMapper productMapper;
    @Autowired
    private ONcFileMapper ncFileMapper;

    /**
     * 查询预览要素
     *
     * @param id 预览要素主键
     * @return 预览要素
     */
    @Override
    public OPreviewElement selectOPreviewElementById(String id)
    {
        return oPreviewElementMapper.selectOPreviewElementById(id);
    }

    /**
     * 查询预览要素列表
     *
     * @param oPreviewElement 预览要素
     * @return 预览要素
     */
    @Override
    public List<OPreviewElement> selectOPreviewElementList(OPreviewElement oPreviewElement)
    {
        return oPreviewElementMapper.selectOPreviewElementList(oPreviewElement);
    }

    /**
     * 新增预览要素
     *
     * @param oPreviewElement 预览要素
     * @return 结果
     */
    @Override
    public int insertOPreviewElement(OPreviewElement oPreviewElement)
    {
        return oPreviewElementMapper.insertOPreviewElement(oPreviewElement);
    }

    /**
     * 修改预览要素
     *
     * @param oPreviewElement 预览要素
     * @return 结果
     */
    @Override
    public int updateOPreviewElement(OPreviewElement oPreviewElement)
    {
        return oPreviewElementMapper.updateOPreviewElement(oPreviewElement);
    }

    /**
     * 批量删除预览要素
     *
     * @param ids 需要删除的预览要素主键
     * @return 结果
     */
    @Override
    public int deleteOPreviewElementByIds(String ids)
    {
        return oPreviewElementMapper.deleteOPreviewElementByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除预览要素信息
     *
     * @param id 预览要素主键
     * @return 结果
     */
    @Override
    public int deleteOPreviewElementById(String id)
    {
        return oPreviewElementMapper.deleteOPreviewElementById(id);
    }

    /**
     * 解析观测数据文件入库
     *
     * @param file
     * @param fileDate
     */
    @Override
    public void parsePreviewFile(File file, String fileDate) {
        InputStreamReader read = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHH");
        formatter.setLenient(false);
        try {
            read = new InputStreamReader(
                    new FileInputStream(file), "UTF-8");//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String line = null;
            try {
                List<OPreviewElement> list = new ArrayList<>();
                while ((line = bufferedReader.readLine()) != null) {
                    OPreviewElement previewElement = new OPreviewElement();
                    previewElement.setId(IdUtils.simpleUUID());
                    previewElement.setCreateDate(new Date());
                    previewElement.setUpdateDate(new Date());
                    previewElement.setObserveFileDate(formatter.parse(fileDate));
                    previewElement.setStation(line.substring(0, 8).trim());
                    previewElement.setLatitude(line.substring(8, 16).trim());
                    previewElement.setLongitude(line.substring(16, 24).trim());
                    previewElement.setDay(line.substring(24, 32).trim());
                    previewElement.setHour(line.substring(32, 40).trim());
                    previewElement.setWindDirection(line.substring(40, 48).trim());
                    previewElement.setWindSpeed(line.substring(48, 56).trim());
                    previewElement.setSeaPressure(line.substring(56, 64).trim());
                    previewElement.setLocalPressure(line.substring(64, 72).trim());
                    previewElement.setAirTemper(line.substring(72, 80).trim());
                    previewElement.setRelativeHumidity(line.substring(80, 88).trim());
                    previewElement.setObserveTime(line.substring(88, 96).trim());
                    previewElement.setSst(line.substring(96, 104).trim());
                    previewElement.setWavePeriod(line.substring(104, 112).trim());
                    previewElement.setWaveHeight(line.substring(112, 120).trim());
                    previewElement.setZonalVelocity(line.substring(120, 128).trim());
                    previewElement.setMeridionalVelocity(line.substring(128, 136).trim());
                    previewElement.setSalinity(line.substring(136, 144).trim());
                    previewElement.setMeasureHeight(line.substring(144, 152).trim());
                    previewElement.setPressure(line.substring(152, 160).trim());
                    previewElement.setHeight(line.substring(160, 168).trim());
                    previewElement.setTemper(line.substring(168, 176).trim());
                    previewElement.setDewPoint(line.substring(176, 184).trim());
                    previewElement.setSpeed(line.substring(184, 192).trim());
                    previewElement.setDirection(line.substring(192, 200).trim());
                    previewElement.setMeasureHeight1000(line.substring(200, 208).trim());
                    previewElement.setHeight1000(line.substring(208, 216).trim());
                    previewElement.setTemper1000(line.substring(216, 224).trim());
                    previewElement.setDewPoint1000(line.substring(224, 232).trim());
                    previewElement.setSpeed1000(line.substring(232, 240).trim());
                    previewElement.setDirection1000(line.substring(240, 248).trim());
                    previewElement.setMeasureHeight850(line.substring(248, 256).trim());
                    previewElement.setHeight850(line.substring(256, 264).trim());
                    previewElement.setTemper850(line.substring(264, 272).trim());
                    previewElement.setDewPoint850(line.substring(272, 280).trim());
                    previewElement.setSpeed850(line.substring(280, 288).trim());
                    previewElement.setDirection850(line.substring(288, 296).trim());
                    previewElement.setMeasureHeight500(line.substring(296, 304).trim());
                    previewElement.setHeight500(line.substring(304, 312).trim());
                    previewElement.setTemper500(line.substring(312, 320).trim());
                    previewElement.setDewPoint500(line.substring(320, 328).trim());
                    previewElement.setSpeed500(line.substring(328, 336).trim());
                    previewElement.setDirection500(line.substring(336, 344).trim());
                    list.add(previewElement);
                }
                oPreviewElementMapper.insertOPreviewElementList(list);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("观测数据入库失败。失败数据：" + line, e);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(read);
        }
    }

    @Override
    public File getPreviewWord(PreviewData previewData, String resultImg) {
        Map<String, String> dataMap = new HashMap<>();
        Date nowDate = new Date();
        String str = DateUtils.format(nowDate, "YYYY年MM月dd日");
        dataMap.put("nowDate", str);
        OProduct product = productMapper.selectOProductById(previewData.getProductId());
        dataMap.put("product", getNotNullString(product.getProductName()));
        dataMap.put("date", getNotNullString(previewData.getDate()));
        ONcFile ncFile = ncFileMapper.selectONcFileById(previewData.getNcFileId());
        dataMap.put("ncFile", getNotNullString(ncFile.getFileName()));
        Map<String, String> workDto = this.generateWorkDto(previewData);
        dataMap.put("time", getNotNullString(workDto.get("tim")));
        dataMap.put("lonMin", getNotNullString(workDto.get("lonMin")));
        dataMap.put("lonMax", getNotNullString(workDto.get("lonMax")));
        dataMap.put("latMin", getNotNullString(workDto.get("latMin")));
        dataMap.put("latMax", getNotNullString(workDto.get("latMax")));
        dataMap.put("yaosu", getNotNullString(previewData.getYaosu()));
        dataMap.put("yaosu2", getNotNullString(previewData.getYaosu2()));
        dataMap.put("type", getType(previewData.getType()));
        //图片   base64
        dataMap.put("resultImg", getImageString(resultImg));
        return WordGenerator.createDoc(dataMap, "preview");
    }
    private String getNotNullString(String str) {
        return str == null ? "" : str;
    }
    private Map<String, String> generateWorkDto(PreviewData previewData) {
        Map<String, String> map = new HashMap<>();
        List<OWorkOrderItem> list = previewData.getWorkDto();
        for (OWorkOrderItem workOrderItem : list) {
            if (workOrderItem.getElement().indexOf("tim") > -1 || workOrderItem.getElement().indexOf("TIM") > -1) {
                map.put("tim", workOrderItem.getMinValue());
            }
            else if (workOrderItem.getElement().indexOf("lon") > -1 || workOrderItem.getElement().indexOf("LON") > -1) {
                map.put("lonMin", workOrderItem.getMinValue());
                map.put("lonMax", workOrderItem.getMaxValue());
            }
            else if (workOrderItem.getElement().indexOf("lat") > -1 || workOrderItem.getElement().indexOf("LAT") > -1) {
                map.put("latMin", workOrderItem.getMinValue());
                map.put("latMax", workOrderItem.getMaxValue());
            }
        }
        return map;
    }
    /**
     * 取图片base64
     *
     * @param imageUrlSrc
     * @return
     */
    private String getImageString(String imageUrlSrc) {
        String tempPath = DictUtils.getDictLabel2("params","TEMP_URL", "/cloud/temp");
        String imageUrl = DictUtils.getDictLabel2("params","IMAGE_URL", "http://115.28.141.125:8098/");
        String filePath = imageUrlSrc.replaceAll(imageUrl, tempPath) + "/";
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            logger.error("文件:" + filePath + ",io异常");
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("文件:" + filePath + ",io异常");
                }
            }
        }
        String encodedString = Base64.getEncoder().encodeToString(data);
        return data != null ? encodedString : "";
    }
}
